package com.controller;

import com.entity.Attachment;
import com.entity.Result;
import com.service.AttachmentService;
import com.utils.IdGen;
import com.utils.MapUtil;
import com.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Controller
public class FileUploadController {

    @Autowired
    private AttachmentService attachmentService;
    private String rootpath = "d://files/";
    @ResponseBody
    @RequestMapping("files/upload")
    public Result upload(MultipartFile file) throws IOException {
        
        // 原始全名称
        String originalFileName = file.getOriginalFilename();
        // 后缀名
        String suffixName = "";
        if (originalFileName.lastIndexOf(".") > -1){
            suffixName = originalFileName.substring(originalFileName.lastIndexOf(".") +1);
        }

        //新文件名
        String uuid = IdGen.uuid();
        //文件路径
        String filepath =  "/files/" + new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + uuid + "." + suffixName;

        File newFile = new File(rootpath + filepath);
        if (!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        Attachment attachment = new Attachment();
        try {
            //保存附件表
            file.transferTo(newFile);
            attachment.setId(uuid);
            attachment.setName(originalFileName);
            attachment.setPath(filepath);
            attachment.preInsert();
            attachment.setFileSize(file.getSize());
            attachment.setSuffix(suffixName);
            attachmentService.insertModel(attachment);
        } catch (IOException e) {
          return ResultUtil.error("上传出错！");
        }
        return ResultUtil.success( MapUtil.buildMap("id",  uuid, "name", originalFileName,"date",attachment.getCreateDate(),"suffix",attachment.getSuffix()));
    }


}
